<template>
  <!-- 新增录入画面对话框-->
  <el-dialog
    :title="form.title"
    center
    :visible.sync="openState"
    width="1024px"
    :close-on-click-modal="false"
    @close="closeFn"
    :before-close="handleClose"
    v-if="openState"
  >
    <el-form ref="editForm" :model="form" :disabled="form.disabled" :rules="rules" label-width="110px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="费项代码" prop="feeCode">
            <el-input v-model="form.feeCode" placeholder="" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-row>
            <el-button
              type="primary"
              icon="el-icon-search"
              :disabled="form.isDisabled"
              plain
              @click="openPayerDialog('feeCode')"
            >
              费项查找
            </el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="分段标志" prop="segmtFlg">
            <el-select v-model="form.segmtFlg" placeholder="" :disabled="form.isDisabled" style="width: 100%">
              <el-option
                v-for="dict in dictMap.FEE_SEGMT_FLG"
                :key="dict.value"
                :label="`${dict.value}-${dict.text}`"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="this.form.segmtFlg !== '1'">
          <el-form-item label="收费模式" prop="feeType">
            <el-select v-model="form.feeType" placeholder="" @change="change" style="width: 100%">
              <el-option
                v-for="dict in dictMap.FEE_TYPE"
                :key="dict.value"
                :label="`${dict.value}-${dict.text}`"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-show="this.form.segmtFlg === '1'">
        <ht-table
          ref="dataTable1"
          :showSerialNumber="false"
          :multi-select="false"
          :initData="false"
          :dictMap="dictMap"
          :reqConfig="reqConfig"
          :queryParams="queryParams"
          :tableBindColumns="tableBindColumns"
          :opButtonList="opButtonList1"
          @dataLoadComplete="dataLoadComplete"
        >
          <template v-slot:operate>
            <el-table-column
              label="操作"
              align="center"
              width="120"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <ht-button-group
                  :buttonList="[
                    {
                      label: '维护',
                      // permission: 'user:xxx:xxx',
                      doFunc: () => {
                        handleAction('update', scope.row);
                      },
                    },
                    {
                      label: '删除',
                      // permission: 'user:xxx:xxx',
                      doFunc: () => {
                        handleAction('del', scope.row, scope.$index);
                      },
                    },
                  ]"
                />
              </template>
            </el-table-column>
          </template>
        </ht-table>
      </div>
      <div v-if="this.form.segmtFlg !== '1'">
        <el-row  v-if="this.form.feeType === '2' || this.form.feeType === '3'">
          <el-col :span="12">
            <el-form-item label="最低手续费" prop="feeMin">
              <ht-amount-input v-model="form.feeMin" placeholder=""></ht-amount-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高手续费" prop="feeMax">
              <ht-amount-input v-model="form.feeMax" placeholder=""></ht-amount-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="this.form.feeType === '1' || this.form.feeType === '3'">
            <el-form-item label="固定金额" prop="fixAmt">
              <ht-amount-input v-model="form.fixAmt" placeholder=""></ht-amount-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="this.form.feeType === '2' || this.form.feeType === '3'">
            <el-form-item label="比例(%)" prop="rate">
              <ht-amount-input v-model="form.rate" placeholder=""></ht-amount-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :loading="isLoading" v-if="form.isDetail">提交</el-button>
      <el-button type="primary" @click="reset" v-if="form.isDetail">重置</el-button>
      <el-button type="primary" @click="closeFn">关闭</el-button>
    </div>
    <detail-dialog
      ref="detailDialog"
      @editComplete="editComplete"
      :dictMap="dictMap"
      :formData="formData"
    ></detail-dialog>
    <search-dialog ref="searchDialog" @confirm="confirmPayer"></search-dialog>
  </el-dialog>
</template>
<script>
import { save, update, detailsApiUrlConfig } from "@/api/cnaps/tips/FeeItemManage/StandardFeeManage.js";
import DetailDialog from "./StandardFeeManageInnerDialog.vue";
import HtAmountInput from "@/views/components/HtAmountInput";
import SearchDialog from "./searchFeeCode.vue";
export default {
  name: "EditInfo",
  components: { DetailDialog, SearchDialog, HtAmountInput },
  props: {
    dictMap: {
      type: Object,
      default: () => {
        return {};
      },
    },
    form: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  computed: {},
  data() {
    return {
      formData: {
        lowAmt:'',
        highAmt:'',
        sFeeMin:'',
        sFeeMax:'',
        feeType:'',
        fixAmt:'',
        rate:'',
      },
      reqConfig: detailsApiUrlConfig,
      isLoading: false,
      list: {},
      newArr: [],
      queryParams: {
        manageType: "",
        feeCode: "",
        feeId: "",
      },
      // 是否显示弹出层
      openState: false,
      // 表单校验
      rules: {
        feeCode: [{ required: true, message: "不能为空", trigger: "blur" }],
        segmtFlg: [{ required: true, message: "不能为空", trigger: "change" }],
        feeType: [{ required: true, message: "不能为空", trigger: "change" }],
        feeMin: [{ required: true, message: "不能为空", trigger: "blur" }],
        feeMax: [{ required: true, message: "不能为空", trigger: "blur" }],
        fixAmt: [{ required: true, message: "不能为空", trigger: "blur" }],
        rate: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
      opButtonList1: () => {
        return [
          {
            label: "新增",
            type: "primary",
            clickFun: () => {
              this.handleAction("add");
            },
          },
          {
            label: "全部删除",
            type: "primary",
            clickFun: () => {
              this.handleAction("delAll");
            },
          },
        ];
      },
      tableBindColumns: [
        { label: `起始金额`, prop: "lowAmt", align: "center", type: "price" },
        {
          label: `截止金额`,
          prop: "highAmt",
          align: "center",
          type: "price",
        },
        {
          label: `段内最低手续费`,
          prop: "sFeeMin",
          align: "center",
          type: "price",
          width: "150",
          formatter: (row) => {
            if (!row.sFeeMin) {
              return "0.00";
            } else {
              return row.sFeeMin;
            }
          },
        },
        {
          label: `段内最高手续费`,
          prop: "sFeeMax",
          align: "center",
          type: "price",
          width: "150",
          formatter: (row) => {
            if (!row.sFeeMax) {
              return "0.00";
            } else {
              return row.sFeeMax;
            }
          },
        },
        {
          label: `固定金额`,
          prop: "fixAmt",
          align: "center",
          type: "price",
        },
        {
          label: `收费模式`,
          prop: "feeType",
          align: "center",
          dictCode: "FEE_TYPE",
        },
        {
          label: `比例(%)`,
          prop: "rate",
          align: "center",
        },
      ],
    };
  },
  watch: {
    form: {
      handler(newValue) {
        if (newValue.segmtFlg === "1") {
          this.$nextTick(() => {
            this.$set(this.queryParams, "id", newValue.id);
            this.$set(this.queryParams, "manageType", newValue.manageType);
            this.$set(this.queryParams, "feeCode", newValue.feeCode);
            this.$set(this.queryParams, "feeId", newValue.feeId);
            this.$refs.dataTable1.doQuery();
          });
        }
        if (newValue.title == "标准手续费新增") {
          this.reqConfig = {};
          this.opButtonList1 = () => {
            return [
              {
                label: "新增",
                type: "primary",
                clickFun: () => {
                  this.handleAction("add");
                },
              },
              {
                label: "全部删除",
                type: "primary",
                clickFun: () => {
                  this.handleAction("delAll");
                },
              },
            ];
          };
        } else {
          this.reqConfig = detailsApiUrlConfig;
          this.opButtonList1 = () => {
            return [
              {
                label: "全部删除",
                type: "primary",
                clickFun: () => {
                  this.handleAction("delAll");
                },
              },
            ];
          };
        }
      },
    },
  },
  methods: {
    dataLoadComplete(res) {
      for (let i = 0; i < res.result.data.length; i++) {
        res.result.data[i].idx = i + 1;
      }
      this.newArr = res.result.data;
      this.showBtn();
    },
    pushData(val) {
      if (val.highAmt != 99999999999999.99) {
        let arr = {
          lowAmt: val.highAmt,
          highAmt: 99999999999999.99,
          sFeeMin: val.sFeeMin,
          sFeeMax: val.sFeeMax,
          feeType: val.feeType,
          fixAmt: val.fixAmt,
          idx: val.idx + 1,
        };
        this.$refs.dataTable1.dataList.push(arr);
      }
    },
    showBtn() {
      if (this.$refs.dataTable1.dataList.length === 0) {
        this.opButtonList1 = () => {
          return [
            {
              label: "新增",
              type: "primary",
              clickFun: () => {
                this.handleAction("add");
              },
            },
            {
              label: "全部删除",
              type: "primary",
              clickFun: () => {
                this.handleAction("delAll");
              },
            },
          ];
        };
      } else {
        this.opButtonList1 = () => {
          return [
            {
              label: "全部删除",
              type: "primary",
              clickFun: () => {
                this.handleAction("delAll");
              },
            },
          ];
        };
      }
    },

    change() {
      this.$set(this.form, "fixAmt", "");
      this.$set(this.form, "rate", "");
      this.$forceUpdate();
    },

    openPayerDialog(fromFlag = "") {
      this.$refs.searchDialog.show(fromFlag);
    },
    confirmPayer(fromFlag, row) {
      if (fromFlag == "feeCode") {
        this.$set(this.form, "feeCode", row.feeCode);
      }
    },
    /** 明细按钮操作 */
    handleAction(type, row, index) {
      this.formData= {
        lowAmt:'',
          highAmt:'',
          sFeeMin:'',
          sFeeMax:'',
          feeType:'',
          fixAmt:'',
          rate:'',
      };
      switch (type) {
        case "add":
          // 明细信息
          this.$set(this.formData, "lowAmt", "0.00");
          this.$set(this.formData, "highAmt", 99999999999999.99);
          this.$set(this.formData, "feeType", "1");
          this.$set(this.formData, "isUpdate", false);
          this.$refs.detailDialog.show();
          break;
        case "delAll":
          this.$refs.dataTable1.dataList.splice(0, this.$refs.dataTable1.dataList.length);
          this.showBtn();
          break;
        case "del":
          this.$confirm("是否删除这条数据？", "系统提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.$refs.dataTable1.dataList.splice(index, 1);
            if(this.$refs.dataTable1.dataList.length>0){
              this.$set(
                this.$refs.dataTable1.dataList[index],
                "lowAmt",
                this.$refs.dataTable1.dataList[index - 1].highAmt
              );
              this.$refs.dataTable1.dataList[index].idx = index;
            }
            this.showBtn();
          });
          break;
        case "update":
          this.formData = _.clone(row);
          if (row.sFeeMin == 0) {
            this.formData.sFeeMin = 0;
          }
          if (row.sFeeMax == 0) {
            this.formData.sFeeMax = 0;
          }
          this.formData.isUpdate = true;
          this.$refs.detailDialog.show();

          break;
      }
    },
    // 表单重置
    reset() {
      this.$refs.dataTable1.dataList.splice(0, this.$refs.dataTable1.dataList.length);
      this.opButtonList1 = () => {
        return [
          {
            label: "新增",
            type: "primary",
            clickFun: () => {
              this.handleAction("add");
            },
          },
          {
            label: "全部删除",
            type: "primary",
            clickFun: () => {
              this.handleAction("delAll");
            },
          },
        ];
      };
      this.resetForm("editForm");
    },
    editComplete(val) {
      this.list = JSON.parse(val);
      if (this.newArr) {
        this.$refs.dataTable1.dataList = this.newArr;
      }
      console.log(this.list.isUpdate)
      if (this.list.isUpdate) {
        if (this.$refs.dataTable1.dataList.length == "1") {
          this.list.idx = 1;
          this.$set(this.$refs.dataTable1.dataList, this.list.idx - 1, this.list);
          if(99999999999999.99!==this.list.highAmt){
            this.pushData(this.list);
          }
          return;
        }
        if (this.$refs.dataTable1.dataList.length > 2) {
          for (let i = 1; i < this.$refs.dataTable1.dataList.length - 1; i++) {
            if (this.list.highAmt > this.$refs.dataTable1.dataList[i].highAmt) {
              this.$refs.dataTable1.dataList.splice(this.list.idx, this.$refs.dataTable1.dataList.length);
              this.$set(this.$refs.dataTable1.dataList, this.list.idx - 1, this.list);
              this.pushData(this.list);
              return;
            } else {
              this.$set(this.$refs.dataTable1.dataList, this.list.idx - 1, this.list);
            }
          }
        }
        if (this.list.lowAmt == "0.00") {
          this.$set(this.$refs.dataTable1.dataList, this.list.idx - 1, this.list);
          this.$set(this.$refs.dataTable1.dataList[this.list.idx], "lowAmt", this.list.highAmt);
        } else {
          this.$refs.dataTable1.dataList.splice(this.list.idx, this.$refs.dataTable1.dataList.length);
          this.$set(this.$refs.dataTable1.dataList, this.list.idx - 1, this.list);
          this.pushData(this.list);
        }
      } else {
        this.list.idx = this.$refs.dataTable1.dataList.length + 1;
        this.$refs.dataTable1.dataList.push(this.list);
        this.pushData(this.list);
        this.showBtn();
      }
    },
    closeFn() {
      this.openState = false;
      this.reset();
      if (this.form.segmtFlg === "1") {
        this.$refs.dataTable1.dataList = [];
        this.showBtn();
      }
    },

    show() {
      this.openState = true;
    },
    submitForm() {
      this.$refs["editForm"].validate((valid) => {
        if (valid && this.form.isDisabled) {
          if (this.form.segmtFlg === "1") {
            this.form.detail = this.$refs.dataTable1.dataList;
            (this.form.fixAmt = ""), (this.form.FeeMin = ""), (this.form.FeeMax = ""), (this.form.rate = "");
          } else {
            if (this.form.feeMin > this.form.feeMax) {
              this.msgError("【最低手续费】不能小于【最高手续费】！");
              return;
            }
            this.form.detail = [];
          }
          this.isLoading = true;
          update(this.form)
            .then(() => {
              this.isLoading = false;
              this.msgSuccess("修改成功");
              this.closeFn();
            })
            .catch((err) => {
              this.isLoading = false;
            });
        } else if (valid && !this.form.isDisabled) {
          if (this.form.segmtFlg === "1") {
            this.form.detail = this.$refs.dataTable1.dataList;
            (this.form.fixAmt = ""), (this.form.sFeeMin = ""), (this.form.sFeeMax = ""), (this.form.rate = "");
          } else {
            if (this.form.feeMin > this.form.feeMax) {
              this.msgError("【最低手续费】不能大于【最高手续费】！");
              return;
            }
            this.form.detail = [];
          }
          this.isLoading = true;
          save(this.form)
            .then(() => {
              this.isLoading = false;
              this.msgSuccess("新增成功");
              this.closeFn();
            })
            .catch((err) => {
              this.isLoading = false;
            });
        }
      });
    },

    handleClose(done) {
      if(this.form.isDetail){
        this.$confirm("确认关闭？")
          .then((_) => {
            this.reset();
            done();
          })
          .catch((_) => {});
      }else{
        this.reset();
        done();
      }
    },
  },
};
</script>
<style>
.label-header-msg {
  font-weight: bold;
}

.form-card {
  margin-bottom: 10px;
}
.el-table__empty-block {
  height: 200px !important;
}
</style>
